//#version 330
// source: http://www.cours.polymtl.ca/inf2705/nuanceurs/exempleIllumination/phong.glsl

uniform int localViewer;
uniform int utiliseTexture;

uniform float facteurZ;
uniform sampler2D displacementMap;

vec3 normal, lightDir;
vec4 diffuse;

float epsilon = 0.0001,NdotL;

//uniform vec4 u_plane0=vec4(0,-1,0,0); // defined in view-space

float Fonc( float x, float y )
{
   float z;
   z = x*x - y*y;
   //z = x*y;
   //z =  y*sin(2.0*x) * x*cos(2.0*y);
   return (0.005*facteurZ) * z;
}

void main( void )
{
   // transformation standard du sommet (ModelView et Projection)

   vec4 v = vec4(gl_Vertex);	
   if (utiliseTexture==0)
   {
        v.z = Fonc(v.x,v.y);

    gl_Position = gl_ModelViewProjectionMatrix * v;

    normal = gl_Normal;
    normal = vec3(-( Fonc((v.x+epsilon) ,v.y) - Fonc((v.x-epsilon) ,v.y) ) / (2.0 * epsilon) , -( Fonc( v.x ,(v.y+epsilon)) -  Fonc( v.x , (v.y-epsilon) ) ) / (2.0 * epsilon)  , 1.0);
    normal = -normalize(gl_NormalMatrix * normal);

    lightDir = normalize(vec3(gl_LightSource[0].position));

    NdotL = max(dot(normal, lightDir), 0.0);

    diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse;
    gl_FrontColor =  NdotL * diffuse;


   gl_ClipVertex = gl_ModelViewMatrix * v;
    vec4 vsPos = gl_ModelViewMatrix * gl_Vertex;

   }
    else
   {
       gl_TexCoord[0] = gl_MultiTexCoord0;
       vec4 hmColor = texture2D(displacementMap,vec2(gl_TexCoord[0]));
       vec4 offset = vec4(gl_Vertex);
       offset.z-=(hmColor.r+hmColor.g+hmColor.b)*facteurZ/(3.0*200.0);
       gl_Position = gl_ModelViewProjectionMatrix * offset;

	    gl_ClipVertex = gl_ModelViewMatrix * v;
   }

}
